/*
 * Copyright 2025 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package androidx.xr.glimmer.benchmark

import androidx.compose.runtime.Composable
import androidx.compose.testutils.LayeredComposeTestCase
import androidx.compose.testutils.benchmark.ComposeBenchmarkRule
import androidx.compose.testutils.benchmark.benchmarkFirstCompose
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.AnnotatedString
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.LargeTest
import androidx.xr.glimmer.GlimmerTheme
import androidx.xr.glimmer.Text
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith

/**
 * Benchmark for [Text] composition costs, to allow for optimizing generated bytecode (for example
 * to avoid excess groups). We do not measure layout / draw performance as this is both difficult to
 * measure consistently (due to text caching at lower levels), and also because this is benchmarked
 * at the [androidx.compose.foundation.text.BasicText] level - our wrapper only has composition
 * level changes.
 */
@LargeTest
@RunWith(AndroidJUnit4::class)
class TextBenchmark {

    @get:Rule val benchmarkRule = ComposeBenchmarkRule()

    private val textString = "Text"
    private val textAnnotatedString = AnnotatedString("Text")

    @Test
    fun first_compose_string_contentColor() {
        benchmarkRule.benchmarkFirstCompose(textTestCase { Text(textString) })
    }

    @Test
    fun first_compose_annotatedString_contentColor() {
        benchmarkRule.benchmarkFirstCompose(textTestCase { Text(textAnnotatedString) })
    }

    @Test
    fun first_compose_string_explicit_color() {
        benchmarkRule.benchmarkFirstCompose(textTestCase { Text(textString, color = Color.Blue) })
    }

    @Test
    fun first_compose_annotatedString_explicit_color() {
        benchmarkRule.benchmarkFirstCompose(
            textTestCase { Text(textAnnotatedString, color = Color.Blue) }
        )
    }
}

private fun textTestCase(textContent: @Composable () -> Unit): () -> LayeredComposeTestCase = {
    object : LayeredComposeTestCase() {
        @Composable
        override fun MeasuredContent() {
            textContent()
        }

        @Composable
        override fun ContentWrappers(content: @Composable () -> Unit) {
            GlimmerTheme { content() }
        }
    }
}
